package com.ark.frigate.zookeeper.service;

import java.util.concurrent.Future;

import org.apache.commons.lang3.RandomUtils;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.AsyncResult;
import org.springframework.stereotype.Service;

import com.ark.frigate.zookeeper.utils.ZookeeperFairLock;
import com.ark.frigate.zookeeper.utils.ZookeeperUnFairLock;

import lombok.extern.slf4j.Slf4j;

/**
 * TODO
 *
 * @author zengweilong
 * @date 8/6/21 4:37 PM
 */
@Slf4j
@Service
public class ZookeeperService {

    @Async("commonAsyncExecutor")
    public Future<String> testThreadLock(String name) throws Exception {
        String result = testLock(name);
        Future<String> future = new AsyncResult<>(result);
        return future;
    }

    public String testLock(String name) throws Exception {
        log.info("开始执行 = {}", name);
        ZookeeperFairLock zookeeperLock = new ZookeeperFairLock("/lock/test", 1000L);
        ZookeeperUnFairLock zookeeperUnFairLock = new ZookeeperUnFairLock("/lock/test2");
        if (zookeeperLock.lock()) {
            int i = RandomUtils.nextInt(100, 1000);
            log.info("休眠时间:{}", i);
            Thread.sleep(i);
            log.info("[获取到Lock] = {}", name);
            zookeeperLock.unLock();
            return name;
        } else {
            log.info("[没有获取到Lock] = {}", name);
            return null;
        }
    }
}
